package org.ysling.litemall.admin.web;
// Copyright (c) [ysling] [927069313@qq.com]
// [litemall-plus] is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of Mulan PSL v2 at:
//             http://license.coscl.org.cn/MulanPSL2
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
// MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
// See the Mulan PSL v2 for more details.

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.ysling.litemall.admin.annotation.RequiresPermissionsDesc;
import org.ysling.litemall.core.utils.response.ResponseUtil;
import org.ysling.litemall.core.validator.Order;
import org.ysling.litemall.core.validator.Sort;
import org.ysling.litemall.db.domain.*;
import org.ysling.litemall.db.service.*;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;

@Slf4j
@RestController
@RequestMapping("/admin/reward")
@Validated
public class AdminRewardController {

    @Autowired
    private LitemallGoodsService goodsService;
    @Autowired
    private LitemallRewardTaskService rewardTaskService;
    @Autowired
    private LitemallRewardService rewardService;

    @RequiresPermissions("admin:reward:listuser")
    @RequiresPermissionsDesc(menu = {"推广管理", "赏金管理"}, button = "查询参与用户")
    @GetMapping("/listuser")
    public Object listuser(Integer userId, Integer taskId, Integer rewardId, Short status,
                           @RequestParam(defaultValue = "1") Integer page,
                           @RequestParam(defaultValue = "10") Integer limit,
                           @Sort @RequestParam(defaultValue = "add_time") String sort,
                           @Order @RequestParam(defaultValue = "desc") String order) {
        return ResponseUtil.okList(rewardService.queryList(userId, taskId, rewardId, status, page, limit, sort, order));
    }

    @RequiresPermissions("admin:reward:list")
    @RequiresPermissionsDesc(menu = {"推广管理", "赏金管理"}, button = "查询")
    @GetMapping("/list")
    public Object list(String goodsId,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        return ResponseUtil.okList(rewardTaskService.querySelective(goodsId, page, limit, sort, order));
    }

    private Object validate(LitemallRewardTask rewardTask) {
        Integer goodsId = rewardTask.getGoodsId();
        if (goodsId == null) {
            return ResponseUtil.badArgument();
        }

        Integer rewardMember = rewardTask.getRewardMember();
        if (rewardMember == null || rewardMember <= 0) {
            return ResponseUtil.badArgument();
        }

        BigDecimal award = rewardTask.getAward();
        if (award == null || award.compareTo(BigDecimal.ZERO) != 1){
            return ResponseUtil.badArgument();
        }
        return null;
    }

    @RequiresPermissions("admin:reward:read")
    @RequiresPermissionsDesc(menu = {"推广管理", "赏金管理"}, button = "详情")
    @GetMapping("/read")
    public Object read(@NotNull Integer id) {
        LitemallRewardTask rewardTask = rewardTaskService.findById(id);
        return ResponseUtil.ok(rewardTask);
    }

    @RequiresPermissions("admin:reward:update")
    @RequiresPermissionsDesc(menu = {"推广管理", "赏金管理"}, button = "编辑")
    @PostMapping("/update")
    public Object update(@RequestBody LitemallRewardTask rewardTask) {
        Object error = validate(rewardTask);
        if (error != null) {
            return error;
        }

        LitemallRewardTask task = rewardTaskService.findById(rewardTask.getId());
        if(task == null) {
            return ResponseUtil.badArgumentValue();
        }
        
        LitemallGoods goods = goodsService.findById(rewardTask.getGoodsId());
        if (goods == null) {
            return ResponseUtil.badArgumentValue();
        }

        rewardTask.setGoodsName(goods.getName());
        rewardTask.setPicUrl(goods.getPicUrl());
        rewardTask.setGoodsPrice(goods.getRetailPrice());
        if (rewardTaskService.updateVersionSelective(rewardTask) == 0) {
            return ResponseUtil.updatedDataFailed();
        }

        return ResponseUtil.ok();
    }

    @RequiresPermissions("admin:reward:create")
    @RequiresPermissionsDesc(menu = {"推广管理", "赏金管理"}, button = "添加")
    @PostMapping("/create")
    public Object create(@RequestBody LitemallRewardTask rewardTask) {
        Object error = validate(rewardTask);
        if (error != null) {
            return error;
        }

        Integer goodsId = rewardTask.getGoodsId();
        LitemallGoods goods = goodsService.findById(goodsId);
        if (goods == null) {
            return ResponseUtil.fail("商品不存在");
        }
        if(rewardTaskService.countByGoodsId(goodsId) > 0){
            return ResponseUtil.fail( "商品已经存在");
        }

        //添加赏金活动信息
        rewardTask.setGoodsName(goods.getName());
        rewardTask.setPicUrl(goods.getPicUrl());
        rewardTask.setGoodsPrice(goods.getRetailPrice());
        rewardTaskService.createRewardTask(rewardTask);
        return ResponseUtil.ok(rewardTask);
    }

    @RequiresPermissions("admin:reward:delete")
    @RequiresPermissionsDesc(menu = {"推广管理", "赏金管理"}, button = "删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody LitemallRewardTask rewardTask) {
        Integer id = rewardTask.getId();
        if (id == null) {
            return ResponseUtil.badArgument();
        }
        rewardTaskService.delete(id);
        return ResponseUtil.ok();
    }
}
